import { useCallback, useEffect, useState } from "react";
import { getStorageData } from "utils";
import {
  Image,
  ScrollView,
  StyleSheet,
  View,
  Text,
  TouchableOpacity,
  AppState,
  type AppStateStatus,
} from "react-native";
import { useFocusEffect } from "@react-navigation/native";
import { manager } from "utils/bleManage";
import { useAppSelector, useAppDispatch } from "app/store";
import { setConnectedDevice } from "app/modules/app";
import toast from "utils/toast";
import translate from "utils/translate";

export default ({ navigation }: RootStackScreenProps) => {
  const [bleList, setBleList] = useState<BindDevice[]>([]);
  const connectedDevice = useAppSelector((state) => {
    return state.app.connectedDevice;
  });
  const dispatch = useAppDispatch();

  useFocusEffect(
    useCallback(() => {
      getStorageData("bleList").then((value) => {
        setBleList(value ? JSON.parse(value) : []);
      });
    }, [])
  );
  useEffect(() => {
    const appStateListener = async (newAppState: AppStateStatus) => {
      if (newAppState === "active") {
        if (connectedDevice) {
          const isDeviceConnected =
            await manager.isDeviceConnected(connectedDevice);
          if (!isDeviceConnected) {
            dispatch(setConnectedDevice(null));
          }
        }
      }
    };
    const subscription = AppState.addEventListener("change", appStateListener);
    return () => {
      subscription.remove();
    };
  }, [connectedDevice]);
  return (
    <View style={styles.container}>
      <ScrollView style={styles.scrollView}>
        <View style={{ alignItems: "center" }}>
          {bleList.map((item, index) => {
            return (
              <View
                key={item.uuid}
                style={{
                  flexDirection: "row",
                  alignItems: "center",
                  justifyContent: "space-between",
                  width: "90%",
                  borderBottomColor: "#f9f9f9",
                  borderBottomWidth: 1,
                }}
              >
                <View style={{ flexDirection: "row", alignItems: "center" }}>
                  <Image
                    style={styles.image}
                    source={require("../../assets/images/ble.png")}
                  ></Image>
                  <Text>{item.name}</Text>
                </View>
                <TouchableOpacity
                  style={{
                    flexDirection: "row",
                    alignItems: "center",
                  }}
                  onPress={() => {
                    if (connectedDevice) {
                      if (connectedDevice == item.uuid) {
                        navigation.push("connect", {
                          ...item,
                          connected: true,
                          index,
                        });
                      } else {
                        return toast(translate("home.bind.tip"));
                      }
                    } else {
                      navigation.push("connect", { ...item, index });
                    }
                  }}
                >
                  <Text
                    style={{
                      color:
                        connectedDevice == item.uuid
                          ? "rgba(10, 89, 247, .8)"
                          : undefined,
                    }}
                  >
                    {connectedDevice == item.uuid
                      ? translate("home.bind.Connected")
                      : translate("home.bind.unconnected")}
                  </Text>
                  <Image
                    style={{
                      width: 24,
                      height: 24,
                      marginLeft: 12,
                    }}
                    source={require("../../assets/images/arrow-right-bold.png")}
                  ></Image>
                </TouchableOpacity>
              </View>
            );
          })}
        </View>
      </ScrollView>
      <TouchableOpacity
        style={styles.button}
        onPress={() => {
          navigation.push("search", {});
        }}
      >
        <Text
          style={{
            textAlign: "center",
            color: "#fff",
          }}
        >
          {translate("home.bind.title")}
        </Text>
      </TouchableOpacity>
    </View>
  );
};
const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: "#fff",
  },
  scrollView: {
    flex: 1,
  },
  image: {
    width: 60,
    height: 67,
  },
  button: {
    backgroundColor: "#0A59F7",
    width: "80%",
    height: 50,
    marginBottom: 30,
    borderRadius: 16,
    alignItems: "center",
    justifyContent: "center",
    alignSelf: "center",
  },
});
